package com.timedomain.him.remake.service;

import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;

import com.timedomain.him.remake.core.AutoStopable;
import com.timedomain.him.remake.core.BasePlayer;
import com.timedomain.him.remake.core.ListPlayer;
import com.timedomain.him.remake.core.NightMode;
import com.timedomain.him.remake.core.PhoneCall;
import com.timedomain.him.remake.ui.NightActivity;
import com.timedomain.him.remake.ui.SplashActivity;
import com.timedomain.him.remake.ui.common.CallingActivity;
import com.timedomain.him.remake.ui.common.PlayerActivity;
import com.timedomain.him.remake.utils.NotificationUtils;

import org.jetbrains.annotations.Nullable;

import java.util.Timer;
import java.util.TimerTask;

public class PlayerService extends Service {

    public static BasePlayer player = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    PowerManager.WakeLock wakeLock = null;

    BroadcastReceiver batteryReceiver = null;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(player == null){
            stopSelf();
            return super.onStartCommand(intent,flags,startId);
        }
        wakeLock = ((PowerManager)getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "himremake:hiscompanion");
        wakeLock.acquire();
        if(player instanceof PhoneCall){

            startForeground(NotificationUtils.notificationId,NotificationUtils.postNoification(this,"正在和「他」进行语音通话","点击返回通话界面", CallingActivity.class));
        }
        else if(player instanceof NightMode){
            startForeground(NotificationUtils.notificationId,NotificationUtils.postNoification(this,"晚安模式","点击返回界面", NightActivity.class));
            IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            batteryReceiver = new BroadcastReceiver(){

                @Override
                public void onReceive(Context context, Intent intent) {
                    int chargingState = intent.getExtras().getInt(BatteryManager.EXTRA_STATUS,BatteryManager.BATTERY_STATUS_UNKNOWN);
                    boolean isCharging = chargingState == BatteryManager.BATTERY_STATUS_CHARGING || chargingState == BatteryManager.BATTERY_STATUS_FULL;
                    if(player != null && player instanceof NightMode){
                        ((NightMode)player).isPhoneCharging = isCharging;
                    }
                }
            };
            registerReceiver(batteryReceiver, filter);
        }
        else if(player instanceof ListPlayer) {
            startForeground(NotificationUtils.notificationId,NotificationUtils.postNoification(this,"正在收听「他」的语音信箱","点击回到播放列表", PlayerActivity.class));

        }else {

            startForeground(NotificationUtils.notificationId,NotificationUtils.postNoification(this,"「他」的陪伴","点击打开界面", SplashActivity.class));
        }
        if(!(player instanceof PhoneCall)){
            player.start();
        }
        else{
            handler.postDelayed(()->{
                if(player != null){
                    player.start();
                }
            },1500);
        }

        if(player instanceof AutoStopable){
            stopMonitor = new Timer();
            stopMonitor.schedule(new TimerTask() {
                @Override
                public void run() {
                    if(player == null || (player instanceof AutoStopable && ((AutoStopable)player).shouldStop())){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                StopPlayerService(PlayerService.this);
                            }
                        });
                    }
                }
            },1000L,1000L);
        }
        return super.onStartCommand(intent,flags,startId);
    }
    Handler handler = new Handler();
    Timer stopMonitor = null;

    public static void StartPlayerService(Context ctx,BasePlayer player){
        if(player != null){
            StopPlayerService(ctx);
        }
        PlayerService.player = player;
        ctx.startService(new Intent(ctx,PlayerService.class));
    }

    public static void StopPlayerService(Context ctx){
        ctx.stopService(new Intent(ctx,PlayerService.class));
        if(player != null){

            player.close();
            player = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(stopMonitor != null){
            stopMonitor.cancel();
        }
        if(batteryReceiver != null){
            unregisterReceiver(batteryReceiver);
        }
        if(wakeLock!=null && wakeLock.isHeld()){wakeLock.release();}
        stopForeground(true);
        if(player != null){
            player.close();
            player = null;
        }
    }
}
